const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const BUILD_DIR = path.join(__dirname, '../build');
const DEBIAN_DIR = path.join(__dirname, '../debian');
const DIST_DIR = path.join(__dirname, '../../dist');

// Create build structure
console.log('Creating Debian package structure...');

const packageRoot = path.join(BUILD_DIR, 'lanchat-server_1.0.0_amd64');

// Clean and create directories
if (fs.existsSync(packageRoot)) {
  fs.rmSync(packageRoot, { recursive: true });
}

fs.mkdirSync(packageRoot, { recursive: true });
fs.mkdirSync(path.join(packageRoot, 'opt/lanchat-server'), { recursive: true });
fs.mkdirSync(path.join(packageRoot, 'DEBIAN'), { recursive: true });
fs.mkdirSync(path.join(packageRoot, 'lib/systemd/system'), { recursive: true });

// Copy application files
console.log('Copying application files...');

const copyRecursive = (src, dest) => {
  if (fs.statSync(src).isDirectory()) {
    fs.mkdirSync(dest, { recursive: true });
    fs.readdirSync(src).forEach(file => {
      copyRecursive(path.join(src, file), path.join(dest, file));
    });
  } else {
    fs.copyFileSync(src, dest);
  }
};

// Copy source files
copyRecursive(
  path.join(__dirname, '../src'),
  path.join(packageRoot, 'opt/lanchat-server/src')
);

// Copy package.json
fs.copyFileSync(
  path.join(__dirname, '../package.json'),
  path.join(packageRoot, 'opt/lanchat-server/package.json')
);

// Copy DEBIAN control files
console.log('Copying DEBIAN control files...');

const debianFiles = ['control', 'postinst', 'prerm', 'postrm'];
debianFiles.forEach(file => {
  const srcPath = path.join(DEBIAN_DIR, 'DEBIAN', file);
  const destPath = path.join(packageRoot, 'DEBIAN', file);

  if (fs.existsSync(srcPath)) {
    fs.copyFileSync(srcPath, destPath);

    // Make scripts executable
    if (file !== 'control') {
      fs.chmodSync(destPath, 0o755);
    }
  }
});

// Copy systemd service file
console.log('Copying systemd service file...');

fs.copyFileSync(
  path.join(DEBIAN_DIR, 'lib/systemd/system/lanchat-server.service'),
  path.join(packageRoot, 'lib/systemd/system/lanchat-server.service')
);

// Build the package
console.log('Building Debian package...');

if (!fs.existsSync(DIST_DIR)) {
  fs.mkdirSync(DIST_DIR, { recursive: true });
}

try {
  execSync(`dpkg-deb --build ${packageRoot}`, { stdio: 'inherit' });

  // Move to dist directory
  const builtPackage = `${packageRoot}.deb`;
  const finalPackage = path.join(DIST_DIR, 'lanchat-server_1.0.0_amd64.deb');

  if (fs.existsSync(builtPackage)) {
    fs.renameSync(builtPackage, finalPackage);
    console.log(`\nPackage built successfully: ${finalPackage}`);
    console.log('\nTo install:');
    console.log(`  sudo dpkg -i ${finalPackage}`);
    console.log('\nTo uninstall:');
    console.log('  sudo apt-get remove lanchat-server');
  }
} catch (error) {
  console.error('Error building package:', error.message);
  process.exit(1);
}
